<?php

namespace App\Http\Controllers\Home;

use App\Models\Configs;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;
use Jenssegers\Agent\Agent;
use Laravel\Socialite\Facades\Socialite;
use Mrgoon\AliSms\AliSms;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    protected $chanel_id = 0;//设置导航选中标志

    public function __construct()
    {
//        $this->middleware('guest', ['except' => 'logout']);
//        view()->share('chanel_id',$this->chanel_id);
    }

    public function sms(Request $request)
    {
        try{
            $type = $request->get('type','');
            $info = Users::where('username',$request->mobile)->first();
            if(empty($type)){
                //验证重复性
                if($info) return $this->writeJson(1,null,'该手机账号已注册');
            }else{
                if(!$info) return $this->writeJson(1,null,'手机账号不存在');
            }
            $cache = cache()->get('sms-'.$request->mobile);
            //20秒的频繁验证
            if($cache && Carbon::now()->timestamp - $cache['time'] < 20){
                return $this->writeJson(1,null,'您的操作太频繁');
            }
            $code = rand(100000,999999);//SMS_141730025  异地登录提醒     SMS_141730027  注册验证码
            $result = (new AliSms())->sendSms($request->mobile, 'SMS_141730027', ['code'=> $code]);
            if($result->Code == 'OK'){
                //保存验证码到缓存用于验证
                $time = Carbon::now()->timestamp;
                //2分钟的过期时间
                cache()->add('sms-'.$request->mobile,['code'=>$code,'time'=>$time],120);
                return $this->writeJson(0);
            }else{
                return $this->writeJson(1,$result,'发送短信失败');
            }
        }catch(\Exception $e){
            return $this->writeJson(1,null,'发送短信失败');
        }
    }

    public function find(Request $request){

        if($request->method() == 'POST'){
            $data = $request->all();
            $user = Users::where('username',$data['username'])->first();
            if(empty($user)) return $this->writeJson(1,null,'手机账号不存在');

            //验证短信验证码
            $cache = cache()->get('sms-'.$data['username']);
            //过期
            if(empty($cache)) return $this->writeJson(1,null,'验证码已过期');
            //正确
            if($cache['code'] != $data['code']) return $this->writeJson(1,null,'验证码输入错误');
            //删除
            cache()->delete('sms-'.$data['username']);

            //字段验证
            $rules = [
                'username' => 'required',
                'code'     => 'required',
                'password' => 'required|min:6|confirmed',
            ];
            $msgs = [
                'username.required' => '请填写手机号码',
                'code.required'     => '请填写短信验证码',
                'password.required' => '请输入新密码',
                'password.min'      => '密码最少6位',
                'password.confirmed'=> '确认密码不一致',
            ];
            $validator = validator()->make($data, $rules ,$msgs);
            if ($validator->fails()) {
                return $this->writeJson(1,null,$validator->errors()->first());
            }
            $user->update(['password'=>bcrypt($data['password'])]);
            return $this->writeJson(0,route('home.auth.login'));
        }else{
            return view('home.auth.find');
        }
    }

    protected function randName(){
        $str = "1234567890qwertyuiopasdfghjklzxcvbnm";
        return substr(str_shuffle($str),mt_rand(0,strlen($str)-11),10);
    }

    //微信登录
    public function weixinLogin(){
        return Socialite::with('weixinweb')->redirect();
    }

    public function weixinReturn(Request $request){
        try{
            //授权成功获取授权用户信息
            $weixin = Socialite::driver('weixinweb')->user();

            //查找用户记录
            $user = Users::where('wechat_id',$weixin->id)->first();
            $agent = new Agent();
            if($user){
                //直接登录
                Auth::login($user, true);
//                $auth = Auth::user();
//                $auth = auth()->guard('web')->user();
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                $auth = auth()->guard('web')->user();
//                dd($auth);
//                if($agent->isMobile()){
//                    return redirect(route('wap.user.index'));
//                }else{
                return redirect(route('home.index.index'));
//                }
            }else{
                //获取账户信息，并跳转到绑定账户信息界面
                $three = [
                    "type" => 'weixin',
                    "idstr" => $weixin->id,
                    "email" => $weixin->email,
                    "name" => $weixin->user['nickname'],
                    "avatar" => $weixin->avatar,
                ];
//                if($agent->isMobile()){
//                    return view('wap.auth.binding',compact('three'));
//                }else{
                    return view('home.auth.binding',compact('three'));
//                }
            }
        }catch(\Exception $e){
//            dd($e);
            abort(500, $e->getMessage());
        }
    }

    public function qqLogin(){
        return Socialite::driver('qq')->redirect();
    }

    public function qqReturn(Request $request){
//        try{
            //授权成功获取授权用户信息
            $qq = Socialite::driver('qq')->user();
            //查找用户记录
            $user = Users::where('qq_id',$qq->id)->first();
//            $agent = new Agent();
            if($user){
                //直接登录
//                $auth = auth()->login($user);
//                auth('web')->login($user);
                Auth::login($user, true);
//                $auth = Auth::user();
//                $auth = auth()->guard('web')->user();
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                $auth = auth()->guard('web')->user();
//                dd($auth);
//                if($agent->isMobile()){
//                    return redirect(route('wap.user.index'));
//                }else{
                return redirect(route('home.index.index'));

//                }
            }else{
                //获取账户信息，并跳转到绑定账户信息界面
                $three = [
                    "type" => 'qq',
                    "idstr" => $qq->id,
                    "email" => $qq->email,
                    "name" => $qq->user['nickname'],
                    "avatar" => $qq->avatar,
                ];
//                if($agent->isMobile()){
//                    return view('wap.auth.binding',compact('three'));
//                }else{
                    return view('home.auth.binding',compact('three'));
//                }
            }
//        }catch(\Exception $e){
//            abort(500, $e->getMessage());
//        }
    }

    public function binding(){
        $three = [
            "type" => 'qq',
            "idstr" =>'51C9BF376685849FDC12BC10E44EDA35',
            "email" => '349202656@qq.com',
            "name" =>  'luoj',
            "avatar" => 'xxxxxx',
        ];
        return view('home.auth.binding',compact('three'));
    }
}